package com.ruoyi.job.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 设备同步定时任务
 * 
 * 调用方式：deviceSyncTask.syncDeviceInfo()
 * 
 * @author ruoyi
 * @date 2025-10-29
 */
@Component("deviceSyncTask")
public class DeviceSyncTask 
{
    private static final Logger log = LoggerFactory.getLogger(DeviceSyncTask.class);
    
    /**
     * 设备服务地址（使用服务名，支持负载均衡）
     * 也可以通过网关调用：http://ruoyi-gateway/device/device
     */
    private static final String DEVICE_SERVICE_URL = "http://ruoyi-device/device";
    
    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * 同步所有设备信息
     * 
     * 定时任务配置示例：
     * 任务名称：同步设备信息
     * 调用方法：deviceSyncTask.syncDeviceInfo()
     * cron表达式：0/10 * * * * ? （每10秒执行一次）
     */
    public void syncDeviceInfo() 
    {
        log.info("开始执行设备信息同步任务...");
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 发送POST请求
            HttpEntity<String> request = new HttpEntity<>(headers);
            ResponseEntity<String> response = restTemplate.exchange(
                DEVICE_SERVICE_URL + "/sync/all",
                HttpMethod.POST,
                request,
                String.class
            );
            
            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("设备信息同步任务执行完成");
            } else {
                log.error("设备信息同步任务执行失败，状态码: {}", response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("执行设备信息同步任务失败: ", e);
            throw new RuntimeException("设备信息同步任务执行失败: " + e.getMessage());
        }
    }
    
    /**
     * 同步单个设备信息（带参数）
     * 
     * @param params 参数格式：deviceId （例如：8）
     */
    public void syncSingleDevice(String params) 
    {
        log.info("开始同步单个设备，参数: {}", params);
        try {
            if (params == null || params.trim().isEmpty()) {
                log.warn("参数为空，无法同步设备");
                return;
            }
            
            String deviceId = params.trim();
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 发送POST请求
            HttpEntity<String> request = new HttpEntity<>(headers);
            ResponseEntity<String> response = restTemplate.exchange(
                DEVICE_SERVICE_URL + "/sync/" + deviceId,
                HttpMethod.POST,
                request,
                String.class
            );
            
            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("设备[{}]同步完成", deviceId);
            } else {
                log.error("设备[{}]同步失败，状态码: {}", deviceId, response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("同步单个设备失败: ", e);
            throw new RuntimeException("同步单个设备失败: " + e.getMessage());
        }
    }
}

